<template>
	<view class="content">
		<view class="sb-info">
			设备名称：{{details.name}}
		</view>
		<!-- <text>连接蓝牙</text> -->
		<view class="bluetooth" v-for="item in BluetoothList">
			{{item.name}}
			<button @click="connetBlue(item)">连接</button>
		</view>
		<view>设备联网</view>
		<picker @change="bindPickerChange" :value="index" :range="array">
			<view class="uni-box">
				<text>{{array[index] || '请选择wifi'}}</text>
				<image src="/static/images/icon.png" mode="widthFix"></image>
			</view>
		</picker>
		<input class="uni-input" type="password" v-model="value" placeholder="请输入密码">
		<button @click="submitWifi">确认</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				details:{},
				array: [],
				index: 0,
				wifiName:'',
				value:'',
				device: {
					deviceId: "",
					name: "",
				},
				uuid: {
					deviceId: '',
					serviceId: '',
					writeId: '',
					notifyId: ''
				},
				getdata:'',
				BluetoothList:[]
			}
		},
		onLoad(options) {
			this.initBlue()
			this.details.name=options.name
			// this.device.deviceId = '48:8F:4C:FE:FC:BE'
			this.getWifis()
			uni.onBluetoothAdapterStateChange(function (res) {
			  console.log('adapterState changed, now is', res)
			})
		},
		onShow() {
			// this.getList()
		},
		onUnload() {
			this.cancelConcent()
			uni.stopBluetoothDevicesDiscovery({
				success(res) {
					// console.log('连接蓝牙成功之后关闭蓝牙搜索');
				}
			})
		},
		mounted() {
			
		},
		methods: {
			gotoPage(e){
				uni.navigateTo({
					url:e
				})
			},
			//项目列表
			async getList(){
				let res = await this.http("get","/tc/tctype/list",{pageNum:1,pageSize:10})
				console.log(res)
			},
			// 打开蓝牙适配器
			initBlue() {
				let that = this
				uni.openBluetoothAdapter({
					success(res) {
						console.log('打开蓝牙适配器成功');
						that.findBlue()
						// that.connetBlue(that.device.deviceId)
					},
					fail() {
						console.log('打开蓝牙适配器失败');
						uni.showToast({
							title: '请打开蓝牙',
							type: 'error',
							icon: 'none'
						})
					}
				})
			},
			// 搜索周边设备
			findBlue() {
				let that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					interval: 0,
					success(res) {
						console.log('设备搜索中');
						uni.onBluetoothDeviceFound(devices => {
							that.getBlue()
						})
					},
					fail() {
						console.log('设备搜索失败');
						uni.showToast({
							icon: 'none',
							title: '无法获取'
						})
					}
				})
			},
			// 获取搜索到的设备信息
			getBlue() {
				let that = this
				that.listShow = !that.listShow
				uni.getBluetoothDevices({
					success(res) {
						console.log(res)
						that.BluetoothList = res.devices.filter((e) => {
							return e.name !== ''
						})
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '无法获取'
						})
					}
				})
			},
			//连接蓝牙
			connetBlue(item) {
				console.log(item)
				let that = this;
				that.device = item
				uni.createBLEConnection({
					deviceId: item.deviceId, //设备id
					success(res) {
						console.log("连接蓝牙成功", res)
						uni.showToast({
							title: '连接中',
							icon: 'loading',
							duration: 2000
						})
						uni.stopBluetoothDevicesDiscovery({
							success(res) {
								// console.log('连接蓝牙成功之后关闭蓝牙搜索');
							}
						})
						that.getServiceId(that.device)
					},
					fail() {
						console.log("连接蓝牙失败!-->11111")
					}
				})
			},
			// 获取蓝牙设备服务
			getServiceId(item) {
				let deviceId = item.deviceId
				let that = this
				setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: deviceId,
						success(res) {
							console.log(res)
							if (res.services.length == 0) {
								uni.showToast({
									icon: 'none',
									title: '设备不可用',
									duration: 1000
								})
							} else {
								that.uuid.deviceId = deviceId
								that.uuid.serviceId = '0000AE30-0000-1000-8000-00805F9B34FB'
								that.getCharacteId(that.uuid)
							}
						},
						fail() {
							uni.showToast({
								icon: 'none',
								title: '获取服务失败'
							})
						}
					})
				}, 1000)
			},
			// 获取蓝牙特征值
			getCharacteId(item) {
				let that = this
				uni.getBLEDeviceCharacteristics({
					deviceId: item.deviceId,
					serviceId: item.serviceId,
					success(res) {
						console.log('获取蓝牙特征值', res)
						that.uuid.writeId = '0000AE01-0000-1000-8000-00805F9B34FB'
						that.uuid.notifyId = '0000AE02-0000-1000-8000-00805F9B34FB'
						that.uuid.deviceId = item.deviceId,
						that.startNotice(that.uuid)
						that.getdata = ''
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '获取特征值失败'
						})
					}
				})
			},
			// 启用 notify 功能
			startNotice(e) {
				let that = this
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: e.deviceId,
					serviceId: e.serviceId,
					characteristicId: e.notifyId,
					success(res) {
						console.log('启用 notify 功能', res)
						//监听设备发送数据
						uni.onBLECharacteristicValueChange((sjRes) => {
							uni.showToast({
								title: '连接中',
								icon: 'loading'
							})
							that.getdata = that.ab2hex(sjRes.value)
							console.log('监听设备发送数据', that.getdata)
							if(sjRes.value){
								setTimeout(()=>{
									uni.hideToast();
								},1000)
							}
						})
					},
					fail() {
						console.log('启用 notify 功能失败')
					}
				})
			},
			// 写入数据
			sendMy(str) {
				let that = this
				//转换数据格式
				uni.writeBLECharacteristicValue({
					deviceId: that.uuid.deviceId, // 蓝牙设备 deviceId
					serviceId: that.uuid.serviceId, // 蓝牙服务uuid,
					characteristicId: that.uuid.writeId, // 蓝牙特征 writeId
					value: str, // 这里的value是ArrayBuffer类型
					writeType: 'write',
					success(res) {
						console.log('指令下发成功', res)
						
					},
					fail(err) {
						console.log('指令发送失败', err)
					}
				})
			},
			stringToHex(str) {
			  let hex = "";
			  for (let i = 0; i < str.length; i++) {
			    let charValue = str.charCodeAt(i).toString(16);
			    hex += charValue.length < 2 ? "0" + charValue : charValue;
			  }
			  return hex;
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			string2buffer(str) {
				let val = ""
				if (!str) return;
				let length = str.length;
				let index = 0;
				let array = []
				while (index < length) {
					array.push(str.substring(index, index + 2));
					index = index + 2;
				}
				val = array.join(",");
				// 将16进制转化为ArrayBuffer
				return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				})).buffer
			},
			// 断开连接
			cancelConcent(e) {
				let that = this
				if (that.device.deviceId !== '--') {
					uni.closeBLEConnection({
						deviceId: that.device.deviceId,
						success(res) {
							console.log(' 断开连接成功', res)
						},
						fail(err) {
							console.log(' 断开连接失败', err)
						},
					})
				}
			},
			//获取wifi
			getWifis(){
				uni.startWifi({
					success:(res)=>{
						// 获取已连接的wifi信息
						uni.getConnectedWifi({
							partialInfo:true,
							success:(res) => {
								console.log("res1",res)
								this.array = [res.wifi.SSID]
								this.wifiName = this.array[0]
							},
						})
					}
				})
			},
			bindPickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.index = e.detail.value
				this.wifiName = this.array[e.detail.value]
			},
			submitWifi(){
				const info = this.wifiName+';'+this.value
				let hexData = this.stringToHex(info)
				let buffer = this.string2buffer(hexData);
				console.log(info)
				this.sendMy(buffer)
			}
		}
	}
</script>

<style lang="less">
	.sb-info{
		width: 100%;
		padding: 20upx;
		box-sizing: border-box;
		margin-bottom: 20upx;
		background-color: #f5f5f5;
	}
	.bluetooth{
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20upx;
		button{
			margin: 0;
			font-size: 24upx;
		}
	}
	.uni-input{
		width: 100%;
		height: 80upx;
		background-color: #f5f5f5;
		margin-bottom: 20upx;
		padding: 0 20upx;
		box-sizing: border-box;
	}
	.uni-box{
		width: 100%;
		height: 80upx;
		background-color: #f5f5f5;
		margin-bottom: 20upx;
		padding: 0 20upx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: space-between;
		
		image {
			width: 40upx;
			height: auto;
		}
	}
</style>